<template>
  <div class="city-wrapper">
    <common-header :title="title"></common-header>
    <city-search :cities="cities"></city-search>
    <city-list :hot="lists.hotCities"
               :cities="cities">
    </city-list>
  </div>
</template>

<script>
import CommonHeader from 'common/header/Header'
import CitySearch from './components/Search'
import CityList from './components/List'
export default {
  name: 'City',
  components: {
    CommonHeader,
    CitySearch,
    CityList
  },
  data () {
    return {
      list: [],
      title: '选择城市'
    }
  },
  computed: {
    lists () {
      const result = []
      const newResult = []
      const hotCities = []
      this.list.map((item) => {
        let alphabet = item.pinyin[0].toUpperCase()
        if (item.rank.toUpperCase() === 'S') {
          hotCities.push(item)
        }
        result.push(alphabet)
      })
      newResult.push(...new Set(result))
      newResult.sort()
      return { newResult, hotCities }
    },
    cities () {
      const result = {}
      this.lists.newResult.map((item) => {
        if (!result[item]) {
          result[item] = []
        }
      })
      for (let key in result) {
        this.list.map((item) => {
          let alphabet = item.pinyin[0].toUpperCase()
          if (alphabet === key) {
            result[alphabet].push(item)
          }
        })
      }
      return result
    }
  },
  methods: {
    getCityInfo () {
      this.$api.city.getCity()
        .then(this.getCityDataSucc)
    },
    getCityDataSucc (res) {
      res = res.data
      if (this.$api.CODE_OK === res.code && res.data) {
        const data = res.data
        this.list = data
      }
    }
  },
  created () {
    this.$nextTick(() => {
      this.getCityInfo()
    })
  },
  deactivated () {
    this.getCityInfo = null
  }
}
</script>

<style lang="stylus" scoped>
.city-wrapper
  touch-action none
</style>
